#!/usr/bin/env python3
import http.server
import socketserver
import ssl
import os

PORT = 3000
DIRECTORY = os.path.dirname(os.path.abspath(__file__))

class Handler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=DIRECTORY, **kwargs)

class QuietTCPServer(socketserver.TCPServer):
    def handle_error(self, request, client_address):
        pass  # 忽略连接重置错误
    
    allow_reuse_address = True  # 允许地址重用

# 绑定到所有接口，支持内网穿透
HOST = "0.0.0.0"  # 监听所有网络接口

try:
    # 尝试加载SSL证书
    context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    context.load_cert_chain('cert.pem', 'key.pem')
    
    with QuietTCPServer((HOST, PORT), Handler) as httpd:
        # 尝试启用HTTPS
        try:
            httpd.socket = context.wrap_socket(httpd.socket, server_side=True)
            protocol = "https"
        except:
            # HTTPS失败，使用HTTP
            protocol = "http"
        
        print(f"游戏服务器已启动在 {HOST}:{PORT}")
        print(f"本地访问: {protocol}://localhost:{PORT}")
        print(f"内网访问: {protocol}://[你的内网IP]:{PORT}")
        print(f"协议: {protocol.upper()}")
        print("支持内网穿透访问")
        print("按 Ctrl+C 停止服务器")
        httpd.serve_forever()
        
except Exception as e:
    print(f"服务器启动失败: {e}")
    print("尝试使用基本HTTP服务器...")
    
    # 回退到基本HTTP服务器
    with QuietTCPServer((HOST, PORT), Handler) as httpd:
        print(f"游戏服务器已启动在 {HOST}:{PORT} (HTTP)")
        print(f"本地访问: http://localhost:{PORT}")
        print(f"如果内网穿透使用HTTPS，请在浏览器中访问HTTP版本")
        print("按 Ctrl+C 停止服务器")
        httpd.serve_forever()